package com.kunchi.platform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kunchi.platform.model.device.DataItem;
import com.kunchi.platform.model.device.Device;
import com.kunchi.platform.model.device.DeviceMode;
import com.kunchi.platform.service.DeviceService;
import com.kunchi.platform.service.LoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

import javax.annotation.Resource;

/**
 * Created by denniszhou on 2017/6/19.
 */
@Service("deviceService")
public class DeviceServiceImpl implements DeviceService {
  @Resource
  LoginService loginService;

  @Value("${baseUrl}")
  private String baseUrl;

  @Value("${login.hash}")
  private String loginHash;

  @Autowired
  RestTemplate restTemplate;

  @Override
  public List<Device> getDeviceList() throws IOException {
    String url = baseUrl + "/devicelist?token={0}&hash={1}";
    String token = loginService.login();
    String response = restTemplate.getForObject(MessageFormat.format(
        url, token, loginHash), String.class);
    String devices = JSONObject.parseObject(response).getString("data");
    return JSON.parseArray(devices, Device.class);
  }

  @Override
  public Device getDevice(String deviceId) throws IOException {
    String url = baseUrl + "/device/{0}?token={1}&hash={2}";
    String token = loginService.login();
    String response = restTemplate.getForObject(MessageFormat.format(
        url, deviceId, token, loginHash), String.class);
    String device = JSONObject.parseObject(response).getString("data");
    return JSON.parseObject(device, Device.class);
  }

  @Override
  public List<DeviceMode> getDeviceModeList() throws IOException {
    String url = baseUrl + "/devicemodelist?token={0}&hash={1}";
    String token = loginService.login();
    String response = restTemplate.getForObject(MessageFormat.format(
        url, token, loginHash), String.class);
    String devices = JSONObject.parseObject(response).getString("data");
    return JSON.parseArray(devices, DeviceMode.class);
  }

  @Override
  public List<DataItem> getDataItemList(String deviceId) throws IOException {
    String url = baseUrl + "/dataitemlist/getDataItemList?token={0}&hash={1}&deviceid={2}";
    String token = loginService.login();
    String response = restTemplate.getForObject(MessageFormat.format(
        url, token, loginHash, deviceId), String.class);
    String items = JSONObject.parseObject(response).getString("data");
    return JSON.parseArray(items, DataItem.class);
  }
}
